const db = uniCloud.database();
const { curTimeStamp } = require('../../common/time');
const { getRandomDesc } = require('../../common/text');
const useScore = require('../../common/score');
module.exports = async function(options = {}) {
	const { characterId, courseId, practiceStats = {}, keystrokeStats = null } = options;
	const { consumingTime = 0, kpm = 0, wpm = 0, successWpm = 0, accuracyKey = 0, accuracyWord = 0, accuracyKeyNoBack = 0, backspaceCount = 0 } = practiceStats;
	const { score, star, integral } = useScore({ kpm, wpm, accuracy: accuracyKey || accuracyWord, backspaceCount });
	if (!characterId || !courseId) {
		throw new Error('缺少角色id或courseId参数');
	}
	// 判断是否是自定义课程
	const isCustom = courseId.indexOf('custom') > -1;
	let collection_course = null;
	let collection_complete = null;
	if (isCustom) {
		collection_course = db.collection('a-dz-course-list-custom');
		collection_complete = db.collection('a-dz-complete-list-custom');
	} else {
		collection_course = db.collection('a-dz-course-list');
		collection_complete = db.collection('a-dz-complete-list');
	}
	const collection_complete_stats = db.collection('a-dz-complete-stats-list');
	const collection_character = db.collection('a-dz-character-list');
	const [characterRes, courseDataRes, courseCompleteRes] = await Promise.all([
		collection_character.where({ characterId }).get(),
		collection_course.where({ courseId }).get(),
		collection_complete.where({ courseId, characterId }).get({ getOne: true }),
		collection_character.where({ _id: characterId }).update({
			integral: db.command.inc(integral)
		})
	]);
	if (characterRes.data.length && characterRes.data[0].type != 'STUDENT') {
		throw new Error('非学生身份不能学习！');
	}
	if (courseDataRes.data.length) {
		const item = courseDataRes.data[0];
		const params = {
			characterId,
			courseId,
			chapter: item.chapter,
			category: item.category,
			courseType: item.courseType,
			language: item.language,
			kpm,
			wpm,
			successWpm,
			rating: star,
			score,
			integral,
			consumingTime,
			backspaceCount,
			accuracyKey,
			accuracyWord,
			accuracyKeyNoBack,
			createTime: curTimeStamp()
		}
		if (item.courseType == 'GAME') params.health = options.health;
		const subArr = [];
		if (courseCompleteRes.data.length > 0) {
			subArr.push(collection_complete.where({ courseId, characterId }).update(params));
		} else {
			subArr.push(collection_complete.add(params));
		}
		if (params.consumingTime > 0 && kpm > 0) {
			if (keystrokeStats) params.keystrokeStats = keystrokeStats;
			subArr.push(collection_complete_stats.add(params));
		}
		await Promise.all(subArr);
		return {
			code: 0,
			data: {
				rating: params.rating,
				score: params.score,
				integral: params.integral,
				tips: getRandomDesc()
			}
		}
	} else {
		return {
			code: -1,
			msg: '操作失败'
		}
	}
}